<template>
	<view>
		<swiper :indicator-dots="false" :autoplay="false" :current="current" :disable-touch="false"
			easing-function="default" @change="onChange" @touchstart="touchStart" @touchend="touchEnd">
			<!-- linear、easeInCubic、easeOutCubic、easeInOutCubic -->
			<!-- 目标 -->
			<swiper-item>
				<view class="swiper-item">
					<image src="https://xd.xdzcy.top/adminuploads/e7e73e7c02be1a009d3dcc23bd14ff7b.png" mode="widthFix"
						class="bg"></image>
					<view class="content">
						<view class="welcome">
							<view class="font-32">欢迎来到Tigo题够</view>
							<view class="font-48 mt-15">请选择您的目标</view>
						</view>
						<view class="target-box">
							<view class="target-item" @click="targetClick(0)"
								:class="targetType == 0 && 'select-click'">
								<image src="/static/entry/yan.png" mode="heightFix" class="target-img"></image>
								<text>考研</text>
							</view>
							<view class="target-item" @click="targetClick(1)"
								:class="targetType == 1 && 'select-click'">
								<image src="/static/entry/bian.png" mode="heightFix" class="target-img"></image>
								<text>考编</text>
							</view>
						</view>
					</view>
					<view class="next" @click="targetNext">下一步</view>
				</view>
			</swiper-item>
			<!-- 岗位类型 -->
			<swiper-item v-if="targetType == 1">
				<view class="swiper-item">
					<image src="https://xd.xdzcy.top/adminuploads/e7e73e7c02be1a009d3dcc23bd14ff7b.png" mode="widthFix"
						class="bg"></image>
					<view class="content">
						<view class="welcome">
							<view class="font-32" style="color:transparent">欢迎来到Tigo题够</view>
							<view class="font-48 mt-15">请选择您的岗位类型</view>
						</view>
						<!-- select选择器 -->
						<view class="select-area">
							<Myselect :options="jobTypeOptions" selectName="jobType" @onSelect="onSelect"
								:backImgType="formData.target" @onSelectClick="handleJobClick"></Myselect>
						</view>
					</view>
					<view class="next" @click="jobNext">下一步</view>
				</view>
			</swiper-item>
			<!-- 院校 -->
			<swiper-item>
				<view class="swiper-item">
					<image src="https://xd.xdzcy.top/adminuploads/e7e73e7c02be1a009d3dcc23bd14ff7b.png" mode="widthFix"
						class="bg"></image>
					<view class="content">
						<view class="welcome">
							<view class="font-32" style="color:transparent">欢迎来到Tigo题够</view>
							<view class="font-48 mt-15">请选择您的院校</view>
						</view>
						<view class="select-area">
							<view class="label">院校</view>
							<Myselect :options="schoolOptions" selectName="school" @onSelect="onSelect"
								:backImgType="formData.target" @onSelectClick="handleSchoolClick"></Myselect>
						</view>
						<view class="select-area" style="margin-top: 30rpx;">
							<view class="label">学科</view>
							<Myselect :options="subjectOptions" selectName="subject" @onSelect="onSelect"
								:backImgType="formData.target" @onSelectClick="handleSubjectClick"></Myselect>
						</view>
						<view class="select-area" style="margin-top: 30rpx;">
							<view class="label">专业</view>
							<Myselect :options="majorOptions" selectName="major" @onSelect="onSelect"
								:backImgType="formData.target" @onSelectClick="handleMajorClick"></Myselect>
						</view>
					</view>
					<view class="next" @click="goIndex">开启学习</view>
				</view>
			</swiper-item>
		</swiper>
		<tn-toast ref="toast"></tn-toast>
	</view>
</template>

<script>
	import Myselect from '@/components/my-select/my-select.vue';
	import loginInfo from '@/api/login.js';
	import entryPageInfo from '@/api/entryPageList.js';
	export default {
		components: {
			Myselect
		},
		data() {
			return {
				current: 0, //当前轮播索引
				targetType: undefined, // 选择类型
				touchStartX: 0,
				formData: {
					target: undefined, // 目标
					jobType: '', // 岗位
					school: '', // 院校
					subject: '', // 学科
					major: '' // 专业
				},
				// 岗位选项组
				jobTypeOptions: [
					{
						id: 1,
						name: "公务员",
						value: 1
					},
					{
						id: 2,
						name: "事业编",
						value: 2
					}
				],
				// 院校选项组
				schoolOptions: [],
				// 学科选项组
				subjectOptions: [],
				// 专业选项组
				majorOptions: [],
			};
		},
		methods: {
			touchStart(e) {
				this.touchStartX = e.touches[0].clientX
			},
			touchEnd(e) {
				const touchEndX = e.changedTouches[0].clientX
				const diffX = touchEndX - this.touchStartX
				if (diffX < 0) {
					if (this.current == 1 && this.isSelectTarget() == false) {
						this.current = 0
						return
					}
					if ( this.current == 2 && this.isSelectJob() == false) {
						this.current = 1
						return
					}
				}
			},
			// 目标点击事件
			targetClick(num) {
				this.formData.target = num;
				this.targetType = num;
			},
			// 岗位点击事件
			async handleJobClick(e) {
				// const {
				// 	show
				// } = e
				// if (show == true) {
				// 	const jobData = await entryPageInfo.getJobListApi();
				// 	if (jobData?.data?.code == 200) {
				// 		this.jobTypeOptions = jobData.data.data.map((item) => {
				// 			return {
				// 				id: item.id,
				// 				name: item.jobName,
				// 				value: item.id
				// 			}
				// 		});
				// 	}
				// }
			},
			// 院校点击事件
			async handleSchoolClick(e) {
				const {
					show
				} = e
				if (show == true) {
					const schoolData = await entryPageInfo.getSchoolAllListApi();
					if (schoolData?.data?.code == 200) {
						const schoolAllList = schoolData?.data?.data.flat();
						this.schoolOptions = schoolAllList.map((item) => {
							return {
								id: item.schoolId,
								name: item.schoolName,
								value: item.schoolId
							}
						});
					}
				}
			},
			// 学科点击事件
			async handleSubjectClick(e) {
				const {
					show
				} = e
				if (show == true) {
					if (this.formData.school == '') {
						this.$refs.toast.show({
							title: '',
							content: '请先选择院校',
							icon: 'warning',
							image: '',
							duration: 1000
						});
						return false
					}
					const subjectData = await entryPageInfo.getSubjectAllApi(this.formData.school.id);
					if (subjectData?.data?.code == 200) {
						this.subjectOptions = subjectData?.data?.data?.departmentModels.map((item) => {
							return {
								id: item.departmentId,
								name: item.departmentName,
								value: item.departmentId
							}
						});
						this.majorOptions = subjectData?.data?.data?.majorModel.map((item) => {
							return {
								id: item.majorId,
								name: item.majorName,
								value: item.majorId,
								majorCode: item.majorCode
							}
						});
					}
				}
			},
			// 专业点击事件
			handleMajorClick(e) {
				const {
					show
				} = e
				if (show == true) {
					if (this.formData.school == '') {
						this.$refs.toast.show({
							title: '',
							content: '请先选择院校',
							icon: 'warning',
							image: '',
							duration: 1000
						})
						return false;
					} else if (this.formData.subject == '') {
						this.$refs.toast.show({
							title: '',
							content: '请先选择学科',
							icon: 'warning',
							image: '',
							duration: 1000
						})
						return false;
					} else {
						return true;
					}
				}
			},
			// 开始学习
			async goIndex() {
				const isKaoyan = this.formData.target == 0;
				const isKaobian = this.formData.target == 1;
			
				// ✅ 考研：校验院校 + 学科
				if (isKaoyan) {
					if (!this.formData.school) {
						this.$refs.toast.show({
							content: '请先选择院校',
							icon: 'warning',
							duration: 1000
						});
						return;
					}
					if (!this.formData.subject) {
						this.$refs.toast.show({
							content: '请先选择学科',
							icon: 'warning',
							duration: 1000
						});
						return;
					}
				}
			
				// ✅ 考编：校验岗位
				if (isKaobian) {
					if (!this.formData.jobType) {
						this.$refs.toast.show({
							content: '请先选择岗位',
							icon: 'warning',
							duration: 1000
						});
						return;
					}
				}
			
				// ✅ 登录或注册
				const token = uni.getStorageSync('token');
				if (!token) {
					await this.handleRegister();
				} else {
					uni.switchTab({
						url: '/pages/index/index'
					});
				}
			},
			// 判断是否选中目标
			isSelectTarget() {
				if (this.targetType == undefined) {
					this.$refs.toast.show({
						title: '',
						content: '请先选择您的目标',
						icon: 'warning',
						image: '',
						duration: 1000
					});
					return false
				} else {
					return true
				}
			},
			// 判断是否选中目标
			isSelectJob() {
				if (this.formData.jobType == "") {
					this.$refs.toast.show({
						title: '',
						content: '请先选择您的岗位',
						icon: 'warning',
						image: '',
						duration: 1000
					});
					return false
				} else {
					return true
				}
			},
			// 目标的下一步事件
			targetNext() {
				if (this.isSelectTarget() == true) {
					this.current = 1
				} else {
					this.current = 0
				}
			},
			// 岗位的下一步事件
			jobNext() {
				if (this.isSelectJob()) {
						this.goIndex();
					}
			},
			// 注册
			async handleRegister() {
			  try {
			    if (this.isSelectTarget()) {
			      // 1. 获取微信 jscode
			      const loginRes = await uni.login({
			        provider: 'weixin',
			        onlyAuthorize: true
			      });
			      const jsCode = loginRes.code;
			
			      // 2. 构建注册参数
			      const isKaoyan = this.formData.target === 0;
			      const isKaobian = this.formData.target === 1;
			
			      let bindCode = '';
			      let bindSchoolId = undefined;
			      let bindDepartmentId = undefined;
			      let bindMajorId = undefined;
			      let bindJobId = undefined;
			
			      if (isKaoyan) {
			        // 考研
			        bindCode = this.formData.major?.majorCode || '';
			        bindSchoolId = this.formData.school?.id;
			        bindDepartmentId = this.formData.subject?.id;
			        bindMajorId = this.formData.major?.id;
			      } else if (isKaobian) {
			        // 考编
			        bindCode = String(this.formData.jobType?.id || '');
			        bindJobId = this.formData.jobType?.id;
			      }
			
			      const data = {
			        bindType: String(this.formData.target), // 0 考研、1 考编
			        bindCode,
			        bindSchoolId,
			        bindDepartmentId,
			        bindMajorId,
			        bindJobId,
			        jsCode
			      };
			
			      // 3. 调用注册接口
			      const res = await loginInfo.registerApi(data);
			
			      // 4. 处理响应
			      if (res.data.code === 200) {
			        // 登录成功，保存 token 和用户信息
			        uni.setStorageSync('token', res.data.data?.token);
			        uni.setStorageSync('userId', res.data.data?.userId);
			        uni.setStorageSync('bindCode', res.data.data?.bindCode);
			        uni.setStorageSync('bindType', res.data.data?.bindType);
			        uni.switchTab({
			          url: '/pages/index/index'
			        });
			      } else if (res.data.code === 500) {
			        // 注册失败，尝试登录
			        this.handleLogin();
			      } else {
			        // 其他错误
			        throw new Error(res.data.message || '注册失败');
			      }
			    }
			  } catch (error) {
			    uni.showToast({
			      title: '注册失败，请重试',
			      icon: 'none'
			    });
			    console.error('注册异常:', error);
			  }
			},
			// 登录
			async handleLogin() {
				try {
					// 1. 获取微信jsCode
					const loginRes = await uni.login({
						provider: 'weixin',
						onlyAuthorize: true
					});
					const jsCode = loginRes.code;
					// 2. 发送jsCode到后端
					const res = await loginInfo.loginApi(jsCode);
					// 3. 处理响应
					if (res.data.code === 200) {
						// 登录成功，保存token和用户信息
						uni.setStorageSync('token', res.data.data?.token);
						uni.setStorageSync('userId', res.data.data?.userId);
						uni.setStorageSync('bindCode', res.data.data?.bindCode);
						uni.setStorageSync('bindType', res.data.data?.bindType);
						uni.switchTab({
							url: '/pages/index/index'
						})
					} else {
						// 处理其他情况
						throw new Error(res.data.data.message || '登录失败');
					}
				} catch (error) {
					uni.showToast({
						title: '登录失败，请重试',
						icon: 'none'
					});
					throw error;
				}
			},
			// 切换轮播图
			async onChange(e) {
				this.current = e.detail.current
			},
			// 选择器选中回调
			onSelect(e) {
				const {
					name,
					value,
				} = e
				this.formData[name] = value; // 保存完整对象
			}
		}
	}
</script>
<style>
	page {
		overflow: hidden;
		background-color: #f8d8cb;

	}
</style>
<style lang="scss" scoped>
	swiper {
		position: fixed;
		left: 0;
		top: 0;
		width: 100vw;
		height: 100vh;
		border-radius: 0;

		swiper-item {
			width: 100%;
			height: 100%;

			border-radius: 0;

			.swiper-item {
				width: 100%;
				height: 100%;
				border-radius: 0;
				position: relative;
				overflow: hidden;



				.bg {
					position: absolute;
					left: 0;
					top: 0;
					width: 200%;
					height: 100%;
					transform: translateX(-20px);
					z-index: -1;
				}

				.content {
					width: 100%;
					height: 100%;
					font-weight: bold;

					.welcome {

						color: #3D3D3D;
						margin: 140rpx 0 0 72rpx;


					}

					.select-area {
						margin-top: 140rpx;
						display: flex;
						align-items: center;
						justify-content: center;

						.label {
							font-size: 32rpx;
							font-weight: 600;
							margin-right: 60rpx;
						}
					}

					.target-box {
						margin: 120rpx 72rpx 0;
						display: flex;
						align-items: center;
						justify-content: space-between;

						.target-item {
							position: relative;
							width: 139px;
							height: 342px;
							display: flex;
							justify-content: center;
							align-items: center;
							opacity: 1;
							border-radius: 20px;
							box-sizing: border-box;

							.target-img {
								position: absolute;
								top: 0;
								left: 0;
								width: 139px;
								height: 342px;
								z-index: -1;
							}
						}
					}
				}

				.next {
					position: absolute;
					left: 120rpx;
					bottom: 140rpx;
					width: 262px;
					height: 47px;
					border-radius: 50px;
					opacity: 1;
					background: #ED7B54;
					color: #fff;
					display: flex;
					align-items: center;
					justify-content: center;
					font-weight: bold;
				}
			}
		}
	}

	.select-click {
		border: 1px solid green;
	}
</style>